//=============================================================================
// DEFINICIO DE LA CLASSE 'DIRECTORYMANAGER'
//=============================================================================
// per Marc Delgado i Alex Tudorache (marcdelgado@gmail.com) | rev. 2012.06.11

#ifndef DIRECTORYMANAGER_HPP
#define	DIRECTORYMANAGER_HPP

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <list>
#include "buffermanager.hpp"
#include "utils.hpp"
#include "variables.hpp"
using namespace std;

//La paraula 'list' era polisèmica.
typedef list<unsigned short> llistaPags;


class directoryManager
{
	public:
		directoryManager(char* disk);
		~directoryManager();
		void close();

		bool make(const string &fileName);
		bool make(const string &fileName, const int &tf, const int &mr, const int &mcc);
		bool del(const string &fileName);
		unsigned short addpag(const string &fileName);
		bool delpag(const string &fileName);
		llistaPags list(const string &fileName);

		//Extras
		properties getProperties(const string &fileName);
		char* readPage(const int pPag);
		void writePage(const int pPag);

	private:
		//Paginador bufferitzat de disc virtual.
		bufferManager* _buffman;
		// Estructura dels registres
		struct slot{
		    string fileName;
		    unsigned short firstPag;
		    unsigned short slotNum;
		    unsigned char tf;
		    unsigned char mr;
		    unsigned char mcc;
		};
		char* _pagCtrl;

        //Mides predefinides d'una capçalera de fitxer.
        static const int _sPath = 6;
        static const int _sNPAG = 2;
        static const int _sTF = 1;
        static const int _sMR = 1;
        static const int _sMCC = 1;
        static const int _sReserved = 1;
        static const int _sHeader = 12;
        static const int _sPage = 1024;

        int getFreePag();
        void setFreePag(const int &n);
        void setUsedPag(const int &n);
        bool isPagInUse(const int &n);

        void setNextPagVal(const int &currPag, const unsigned short &nextPag);
        unsigned short getNextPagVal(const int &pag);

		slot getSlot(const int &n);
		slot getSlot(const string &fileName);
		void setSlot(const slot &s);
		bool validSlot(const int &n);

		void newControl();
        unsigned short getFreeSlot();
        void setFreeSlot(const int &n);
        void deleteSlot(const int &n);

        unsigned short readUShort(const int &pos1, const int &pos2);
        void writeUShort(const unsigned short &valor, const int &pos1, const int &pos2);
};

#endif
